import { useState, forwardRef, useImperativeHandle } from 'react'
const Tab = forwardRef((props, ref) => {
  let style;
  const [index, setIndex] = useState(0)
  const {
    color = 'rgb(190, 170, 146)',
    selectColor = 'rgb(235, 185, 128)',
    width,
    items = [],
    fontSize = '2rem',
    height = '4rem',
    count,
    onClick = () => { }
  } = props
  //根据索引号判断切换为哪一个tab
  const selectStyle = (i) => {
    if (index === i) {
      return {
        color: selectColor,
        borderBottom: `0.2rem solid ${selectColor}`,
      }
    }
    else {
      return {}
    }
  }
  useImperativeHandle(ref, () => ({
    checkTab (index) {
      setIndex(index)
    }
  }))
  function ClickTab (index) {
    setIndex(index);
    onClick(index)
  }
  if (!count || items.length <= count) {
    style = {
      display: 'flex',
      width: width ? width : '100%',

    };
  }
  else {
    style = {
      width: width ? width : '100%',
      whiteSpace: 'nowrap',
      overflowX: 'scroll',
    }
  }

  return (
    <div style={style}>
      {items.map((item, i) => (
        <div style={{
          flex: '1',
          display: 'inline-block',
          color,
          width: items.length < count ? '' : `${100 / count}%`,
          height,
          fontSize,
          textAlign: 'center',
          lineHeight: height,
          userSelect: 'none',
          ...selectStyle(i)
        }}
          key={i}
          onClick={ClickTab.bind(this, i)}>
          {item}</div>
      ))}
    </div>
  )
})
export default Tab;